package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;


    @PostMapping("/submit")
    public R orders(@RequestBody Orders orders){
        ordersService.saveWithDetail(orders);
        return R.success("下单成功");
    }

    //TODO OrderDto
    @GetMapping("/userPage")
    public R getByPage(int page,int pageSize){
        Page p = new Page(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getCheckoutTime);
        Page res = ordersService.page(p, wrapper);
        return R.success(res);
    }

    @GetMapping("/list")
    public R getOrders(){
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getCheckoutTime);
        List<Orders> list = ordersService.list(wrapper);
        return R.success(list);
    }

    @PostMapping("/again")
    public R orderAgain(@RequestBody Orders orders){
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(wrapper);
        return R.success(list);
    }
}
